import {ref} from "vue";

import {regionTree} from '@/api/site.js'
import stomp from "@/variable/Stomp";


export const siteTree = ref([])   // 站点树状列表（用于站点列表）
export let siteList = ref([])     // 站点列表【用于地图上站点绘制】
export let onlineStatu = ref({})  // 用于接收websocket推送站点是否在线状态改变

export const getTree = () => {
  return new Promise((resolve,reject)=>{
    regionTree()
    .then(resp => {
      if(resp.code===200){
        siteTree.value = resp.data
        getTreeList()
        resolve(siteTree.value)
      }
    }).catch(err=>{
      reject(err)
    })
  })
 
}

const getTreeList = ()=>{
  siteList.value = []
  for (let i = 0; i < siteTree.value.length; i++) {
    let regions = siteTree.value[i].regions;
    for (let region of regions) {
      let stationList = region.stationInfoList
      for (let j = 0; j < stationList.length; j++) {
        let data = stationList[j];
        siteList.value.push(data)
      }
    }
  }
}

const subscribeTree = ()=>{
  stomp.subscribe('/topic/onStateChange', (message) => {
    onlineStatu.value = message
    setTree(message)
    getTreeList()
  })
}
subscribeTree()
const setTree = (data)=>{
  for(let i=0,l=siteTree.value.length;i<l;i++){
    let province = siteTree.value[i]
    for(let j=0,l1=province.regions.length;j<l1;j++){
      let regions = province.regions[j]
      for(let k=0,l2=regions.stationInfoList.length;k<l2;k++){
        let station = regions.stationInfoList[k]
        if(station.id===data.id){
          station.online = data.state===1
          return
        }
      }
    }   
  }
}

// 模拟socket推送站点信息
export const test = (data)=>{
  onlineStatu.value = data;
  setTimeout(()=>{
    setTree(data)
  },5000)
}

